//
//  TXKitMacro.h
//  TXKit
//
//  Created by YM on 2017/5/13.
//  Copyright © 2017年 Tincent. All rights reserved.
//

#import <UIKit/UIKit.h>

#ifndef TXKitMacro_h
#define TXKitMacro_h


//******************************************************************************************************************
// Device

/**
 *  System info
 */
#define TX_SYS_VERSION                       ([UIDevice currentDevice].systemVersion)
#define TX_SYS_FLOAT_VERSION                 ([[[UIDevice currentDevice] systemVersion] floatValue])

#define TX_IS_IOS_V(i)                       ([[[UIDevice currentDevice] systemVersion] floatValue] >= i)
#define TX_IS_IOS501                         (TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= 50100)
#define TX_IS_IOS51                          (TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= 51000)
#define TX_IS_IOS6                           ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
#define TX_IS_IOS7                           ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
#define TX_IS_IOS8                           ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
#define TX_IS_IOS9                           ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)
#define TX_IS_IOS10                          ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0)
#define TX_IS_IOS11                          ([[[UIDevice currentDevice] systemVersion] floatValue] >= 11.0)

#define TX_IS_SDK7                           (__IPHONE_OS_VERSION_MAX_ALLOWED >= 70000)

/**
 *  Device info
 */
#define TX_IS_IPHONE        (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define TX_IS_PAD           (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define TX_IS_RETINA        ([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)] && ([UIScreen mainScreen].scale >= 2.0 || [UIScreen mainScreen].scale >= 3.0))

#define TX_IPHONE4_WIDTH                    320.0
#define TX_IPHONE5_WIDTH                    320.0
#define TX_IPHONE6_WIDTH                    375.0
#define TX_IPHONE6PLUS_WIDTH                414.0
#define TX_IPHONEX_WIDTH                    375.0
#define TX_IPHONE4_HEIGHT                   480.0
#define TX_IPHONE5_HEIGHT                   568.0
#define TX_IPHONE6_HEIGHT                   667.0
#define TX_IPHONE6PLUS_HEIGHT               736.0
#define TX_IPHONEX_HEIGHT                   812.0

//UI design base on with designer
#define UI_DESIGN_BASE_RESOLUTION_WIDTH     TX_IPHONE6_WIDTH
#define UI_DESIGN_BASE_RESOLUTION_HEIGHT    TX_IPHONE6_HEIGHT

#define TX_IS_IPHONE4_OR_LESS        (TX_IS_IPHONE && TX_SCREEN_HEIGHT < 568)
#define TX_IS_IPHONE4                (TX_IS_IPHONE && TX_SCREEN_HEIGHT == 480) //320x480
#define TX_IS_IPHONE5                (TX_IS_IPHONE && TX_SCREEN_HEIGHT == 568) //320x568
#define TX_IS_IPHONE5_OR_LESS        (TX_IS_IPHONE && TX_SCREEN_HEIGHT <= 568)
#define TX_IS_IPHONE6                (TX_IS_IPHONE && TX_SCREEN_HEIGHT == 667) //375x667
#define TX_IS_IPHONE6PLUS            (TX_IS_IPHONE && TX_SCREEN_HEIGHT == 736) //414x736
#define TX_IS_IPHONE6PLUS_OR_MORE    (TX_IS_IPHONE && TX_SCREEN_HEIGHT > 667)
#define TX_IS_IPHONEX                (TX_IS_IPHONE && TX_SCREEN_HEIGHT >= 812)

/**宽度比例*/
#define TXScaleWidth(__VA_ARGS__)    ([UIScreen mainScreen].bounds.size.width/375)*(__VA_ARGS__)
/**高度比例*/
#define TXScaleHeight(__VA_ARGS__)   ([UIScreen mainScreen].bounds.size.height/667)*(__VA_ARGS__)
/**字体比例*/
#define TXScaleFont(__VA_ARGS__)     ([UIScreen mainScreen].bounds.size.width/375)*(__VA_ARGS__)

/**
 *  Screen info
 */
#define TX_SCREEN_BOUNDS           [[UIScreen mainScreen] bounds]
#define TX_SCREEN_WIDTH            [[UIScreen mainScreen] bounds].size.width
#define TX_SCREEN_HEIGHT           [[UIScreen mainScreen] bounds].size.height

#define TX_ADAPTED_WIDTH(size)     (size*TX_SCREEN_WIDTH/UI_DESIGN_BASE_RESOLUTION_WIDTH)
#define TX_ADAPTED_HEIGHT(size)    (size*TX_SCREEN_HEIGHT/UI_DESIGN_BASE_RESOLUTION_HEIGHT)

#define TX_ADAPTED_SIZE(size)      (size*TX_SCREEN_WIDTH/UI_DESIGN_BASE_RESOLUTION_WIDTH)

#define TX_STATUSBAR_HEIGHT        (TX_IS_IPHONEX ? 44 : 20)
#define TX_NAVBAR_HEIGHT           (TX_SYS_FLOAT_VERSION < 7.0 ? 44 : (TX_IS_IPHONEX ? 88 : 64))
#define TX_TABBAR_HEIGHT           50

#define TX_SAFEAREA_TOP_HEIGHT (([[UIScreen mainScreen] bounds].size.height<812) ? 20 : 44)

#define TX_SAFEAREA_BOTTOM_HEIGHT \
^double(){\
    if (@available(iOS 11.0, *)) { \
        return [UIApplication sharedApplication].keyWindow.safeAreaInsets.bottom; \
    } else { \
        return 0.0; \
    } \
}()\

#define TX_KEYBOAED_HEIGHT         252.0f
#define TX_KEYBOAED_HEIGHT_MIN     216.0f


//******************************************************************************************************************
// Font & Color

/**
 *  Font
 */
#define TX_FONT(size_float)             ([UIFont fontWithName:@"PingFang-SC-Regular" size:TX_ADAPTED_SIZE(size_float)] ? [UIFont fontWithName:@"PingFang-SC-Regular" size:TX_ADAPTED_SIZE(size_float)] : [UIFont systemFontOfSize:TX_ADAPTED_SIZE(size_float)])

#define TX_FONT_MEDIUM(size_float)      ([UIFont fontWithName:@"PingFang-SC-Medium" size:TX_ADAPTED_SIZE(size_float)] ? [UIFont fontWithName:@"PingFang-SC-Medium" size:TX_ADAPTED_SIZE(size_float)] : [UIFont boldSystemFontOfSize:TX_ADAPTED_SIZE(size_float)])

#define TX_FONT_BOLD(size_float)        ([UIFont fontWithName:@"PingFang-SC-Bold" size:TX_ADAPTED_SIZE(size_float)] ? [UIFont fontWithName:@"PingFang-SC-Bold" size:TX_ADAPTED_SIZE(size_float)] : [UIFont boldSystemFontOfSize:TX_ADAPTED_SIZE(size_float)])

/**
 *  Color
 */
#define TX_RGBA(r,g,b,a)                           ([UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a])
#define TX_RGB(r,g,b)                              (TX_RGBA(r,g,b,1.0f))

#define TX_CG_RGBA(r,g,b,a)                        ([TX_RGBA(r,g,b,a) CGColor])
#define TX_CG_RGB(r,g,b,a)                         ([TX_RGBA(r,g,b,1.0f) CGColor])

#define TX_COLOR_FROM_RGBA(rgbValue,alphaValue)    ([UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:alphaValue])
#define TX_COLOR_FROM_RGB(rgbValue)                (TX_COLOR_FROM_RGBA(rgbValue,1.0f))


//******************************************************************************************************************
// Utility

/**
 *  AppDelegate instance
 */
#define TX_APP_DELEGATE                 ((AppDelegate*)[[UIApplication sharedApplication] delegate])

/**
 *  App info
 */
#define TX_APP_NAME                     [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]
#define TX_APP_BUILD                    [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]
#define TX_APP_VERSION                  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]
#define TX_CURRENT_LANGUAGE             ([[NSLocale preferredLanguages] objectAtIndex:0])

/**
 *  Read bundle file
 */
#define TX_READ_BUNDLE(fn)              [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:fn withExtension:@"bundle"]]

/**
 *  Directory
 */
#define TX_DOCUMENT_PATH(path)          [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] \
stringByAppendingPathComponent:path]
#define TX_CACHE_PATH(path)             [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] \
stringByAppendingPathComponent:path]

/**
 *  Load image
 */
#define TX_LOAD_IMG(fn,imgType)         [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fn ofType:imgType]]
#define TX_LOAD_PNG(fn)                 [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fn ofType:@"png"]]

/**
 *  Thread
 */
#define TX_THREAD_BACK(block)           dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)
#define TX_THREAD_MAIN(block)           dispatch_async(dispatch_get_main_queue(),block)
#define TX_THREAD_AFTER(time, block)    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), block)

//safe thread
#define dispatch_main_sync_safe(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_sync(dispatch_get_main_queue(), block);\
}

#define dispatch_main_async_safe(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}

/**
 *  UserDefaults
 */
#define TX_USER_DEFAULTS    \
    [NSUserDefaults standardUserDefaults]

#define TX_SAVEOBJECT_TO_USERDEFAULTS(key, value)    \
    [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];    \
    [[NSUserDefaults standardUserDefaults] synchronize];

#define TX_GETOBJECT_FROM_USERDEFAULTS(key)    \
    [[NSUserDefaults standardUserDefaults] objectForKey:key]

#define TX_REMOVEOBJECT_FROM_USERDEFAULTS(key)    \
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];    \
    [[NSUserDefaults standardUserDefaults] synchronize];

/**
 *  App is first launch
 */
#define TX_APP_IS_FIRST_LAUNCH    \
    (![[NSUserDefaults standardUserDefaults] boolForKey:@"appLaunched"])

#define TX_SET_APP_LAUNCHED    \
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"appLaunched"];\
    [[NSUserDefaults standardUserDefaults] synchronize];

/**
 *  Text Size
 */

#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
    #define TX_TEXTSIZE(text, font)    [text length] > 0 ? [text sizeWithAttributes:@{NSFontAttributeName:font}] : CGSizeZero;
#else
    #define TX_TEXTSIZE(text, font)    [text length] > 0 ? [text sizeWithFont:font] : CGSizeZero;
#endif

#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
    #define TX_MULTILINE_TEXTSIZE(text, font, maxSize, mode)    [text length] > 0 ? [text \
        boundingRectWithSize:maxSize options:(NSStringDrawingUsesLineFragmentOrigin) \
        attributes:@{NSFontAttributeName:font} context:nil].size : CGSizeZero;
#else
    #define TX_MULTILINE_TEXTSIZE(text, font, maxSize, mode)    [text length] > 0 ? [text \
        sizeWithFont:font constrainedToSize:maxSize lineBreakMode:mode] : CGSizeZero;
#endif

/**
 *  Secure String
 */
#define TX_STRING(object)           (object == nil ? @"":[NSString stringWithFormat:@"%@", object])
#define TX_ARRAY(object)            ( ((object == nil) || ([object isEqual:[NSNull null]])) ? @[] : object )
#define TX_DICTIONARY(object)       ( ((object == nil) || ([object isEqual:[NSNull null]])) ? @{} : object )
#define TX_DIC_VALUE(dic, key)      ( (!dic || ![dic isKindOfClass:[NSDictionary class]] || [dic valueForKey:key] == nil || [dic valueForKey:key] == [NSNull null]) ? @"" : [dic valueForKey:key] )

/**
 *  View SafeArea
 */
#define TX_VIEW_SAFEAREA_INSETS(view) ({UIEdgeInsets i; if(@available(iOS 11.0, *)) {i = view.safeAreaInsets;} else {i = UIEdgeInsetsZero;} i;})

/**
 *  ScrollView Inset Never
 */
#define TX_ADJUSTS_SCROLLVIEW_INSETNEVER(controller, scrollView) if(@available(iOS 11.0, *)) {scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;} else if([controller isKindOfClass:[UIViewController class]]) {controller.automaticallyAdjustsScrollViewInsets = NO;}

/**
 *  Weak object
 */
#define TX_WS(weakSelf)             __weak __typeof(&*self)weakSelf = self;
#define TX_WO(weakObj, obj)         __weak __typeof(&*obj)weakObj = obj;
#define TX_SO(strongSelf, obj)      __strong __typeof(&*self)strongSelf = obj;

/**
 *  取四舍五入整数值
 */
#define TX_ROUNDING_VALUE(value)    (((NSInteger)(value * 10 + 5))/10)

/**
 *  CollectionView Item的实际大小
 */
#define TXColItemWidth(sectionInsetLeft, itemHorSpace, itemCount)   ((((TX_SCREEN_WIDTH-sectionInsetLeft*2-itemHorSpace*(itemCount-1)) - (CGFloat)(((NSInteger)(TX_SCREEN_WIDTH-sectionInsetLeft*2-itemHorSpace*(itemCount-1))) % itemCount) ) / (itemCount*1.0f)) - 1.0f)
#define TXColItemHeight(itemWidth, orgWdith, orgHeight)             (itemWidth * orgHeight * 1.0f / ( orgWdith * 1.0f))

/**
 *  Alert Dialog
 */
#define TX_ALERT(fmt)    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:fmt  delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil,nil]; [alert show];

/**
 *  Toast message
 */
#define TX_TOAST(msg)    [[TXToastCenter defaultCenter] postAlertWithMessage:msg];

/**
 *  Loading View
 */

//Show Loading
#define TX_SHOWLOADING(inView)          [MBProgressHUD TXShowHUDInView:inView];
//Hide Loading
#define TX_HIDELOADING(inView)          [MBProgressHUD TXHideHUDForView:inView];

//Show Loading in KeyWindow
#define TX_SHOWLOAGIND_IN_KEYWINDOW     TX_SHOWLOADING([UIApplication sharedApplication].keyWindow)
//Hide Loading in KeyWindow
#define TX_HIDELOADING_FOR_KEYWINDOW    TX_HIDELOADING([UIApplication sharedApplication].keyWindow)

/**
 *  移除iOS7之后，cell默认左侧的分割线边距
 */
#define kTXRemoveCellSeparator    \
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{\
cell.separatorInset = UIEdgeInsetsZero;\
cell.layoutMargins = UIEdgeInsetsZero; \
cell.preservesSuperviewLayoutMargins = NO; \
}


//******************************************************************************************************************
// Log

/**
 *  Log Print
 */

#ifdef DEBUG

#define TXLog( s, ... )           NSLog( @"<%@:(%d)> %@", [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#define TXLogVerbose( s, ... )    NSLog( @"<%@:(%d)> %@", [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#define TXLogDebug( s, ... )      NSLog( @"<%@:(%d)> %@", [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#define TXLogInfo( s, ... )       NSLog( @"<%@:(%d)> %@", [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#define TXLogWarn( s, ... )       NSLog( @"<%@:(%d)> %@", [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#define TXLogError( s, ... )      NSLog( @"<%@:(%d)> %@", [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )

#else //DEBUG

#define TXLog( s, ... )
#define TXLogVerbose( s, ... )
#define TXLogDebug( s, ... )
#define TXLogInfo( s, ... )
#define TXLogWarn( s, ... )
#define TXLogError( s, ... )

#endif //DEBUG


#endif /* TXKitMacro_h */
